<?php
/**
 * resize image.
 * @package Util
 * @author nullstring
 */
class ImageResize {
        protected $sourceImage;
        protected $newImage = object;
        protected $imageType;
    protected $origDimension = array();
    protected $newDimension = array();

        public function __construct($sourceImage, $maxWidth = 800, $maxHeight = 600) {
                $this->sourceImage = $sourceImage;

                $picInfos = getimagesize($this->sourceImage);
                $this->oldDimension["width"]  = $picInfos[0];
                $this->oldDimension["height"] = $picInfos[1];

                $typeArray = explode("/", $picInfos["mime"]);
                $this->imageType = $typeArray[1];

                if ($this->oldDimension["width"] > $maxWidth & $this->oldDimension["height"] <= $maxHeight) {
                        $ratio = $maxWidth / $this->oldDimension["width"];
                } elseif ($this->oldDimension["height"] > $maxHeight & $this->oldDimension["width"] <= $maxWidth) {
                        $ratio = $maxHeight / $this->oldDimension["height"];
                } elseif ($this->oldDimension["width"] > $maxWidth & $this->oldDimension["height"] > $maxHeight) {
                        $ratio1 = $maxWidth / $this->oldDimension["width"];
                        $ratio2 = $maxHeight / $this->oldDimension["height"];
                        $ratio  = ($ratio1 < $ratio2) ? $ratio1 : $ratio2;
                } else {
                        $ratio = 1;
                }

                $this->newDimension["width"]   = floor($this->oldDimension["width"] * $ratio);
                $this->newDimension["height"]  = floor($this->oldDimension["height"] * $ratio);
        }

    public function generateImage()
    {
                if ($this->imageType == "jpeg") {
                        $origPic = imagecreatefromjpeg($this->sourceImage);
                } elseif ($this->imageType == "png") {
                        $origPic = imagecreatefrompng($this->sourceImage);
                }

                $this->newImage = imagecreatetruecolor($this->newDimension["width"], $this->newDimension["height"]);
                imagecopyresampled($this->newImage, $origPic, 0, 0, 0, 0, $this->newDimension["width"], $this->newDimension["height"], $this->oldDimension["width"], $this->oldDimension["height"]);
    }

    public function getNewDimension()
    {
        return $this->newDimension;
    }

        public function saveTo($name, $path = "") {
        	if ($this->imageType == "jpeg") {
        		imagejpeg($this->newImage, $path . "/" . $name, 100);
        	} elseif ($this->imageType == "png") {
            	imagepng($this->newImage, $path . "/" . $name, 100);
            }
        }

}

?>